<template>
  <div class="space">
    <div class="user-info">
      <div class="user-avatar">
<!--        <img :src="userInfo.avatar" alt="" />-->
      </div>
      <div class="user-main">
<!--        <h1>{{ userInfo.name }}</h1>-->
        <div style="color: #999">
          个人信息：<!--<span>{{ userInfo.sign }}</span>-->
        </div>
        <span class="info">
<!--          {{ userInfo.createdAt }}-->
          <em>随手帮，生活帮，学习还帮</em>
          |
          <el-button @click.native.prevent="dialogFormVisible=true" type="text" size="marge">
              编辑个人资料
          </el-button>
        </span>
      </div>
      <el-row :gutter="20">
        <el-col :span="16"><div class="grid-content bg-purple">
          <div style="margin-bottom: 10px; background-color: white; border-radius: 4px;box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);">
            <el-descriptions style="padding: 10px" class="margin-top" title="个人信息展示：" :column="3" border>
              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-user"></i>
                  用户名
                </template>
                {{userData.username}}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-user"></i>
                  真实姓名
                </template>
                {{userData.realName}}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-mobile-phone"></i>
                  手机号
                </template>
                {{ userData.tel }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-location-outline"></i>
                  区域所在位置
                </template>
                {{ userData.bedroomAddr }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-tickets"></i>
                  身份标签：
                </template>
                <el-tag size="small">成都大学-学生</el-tag>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  备注
                </template>
                {{userData.remark}}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </div></el-col>
        <el-col :span="8"><div class="grid-content bg-purple">
          <div style="margin-bottom: 10px; background-color: white; border-radius: 4px;box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);">
            <div style="padding: 10px">个人信誉：（满分100分）</div>
            <div>
              <el-progress style="padding: 10px" type="circle" :percentage="userData.reputation"></el-progress>
            </div>
          </div>
          <span style="color: gray;float:right;">温馨提示：单个接收任务，如果逾期未完成的话，会被扣5分的哦~，低于80分将不得接收任务！</span>
        </div></el-col>
      </el-row>
    </div>

    <!-- v-model="activeName" -->
    <el-tabs class="user-nav" v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="已发布任务" name="1"></el-tab-pane>
      <el-tab-pane label="已接受任务（他人）" name="2"></el-tab-pane>
      <el-tab-pane label="未接收的任务（自己）" name="3"></el-tab-pane>
    </el-tabs>

    <div class="user-info-show">
      <el-empty v-if="isAdmin" description="你是管理员叭，糟糕，没有这个模块哦~"></el-empty>
      <div v-else >
        <el-card shadow="hover">
          <div slot="header" class="clearfix">
            <span>我的任务</span><span style="color: grey;font-size: 20px">&nbsp;注意：灰色任务表示已完成。</span>
          </div>
          <div class="infinite-list-wrapper" style="overflow:auto">
            <ul
              class="list"
              v-infinite-scroll="load"
              infinite-scroll-disabled="disabled">
              <div v-for="item in tableData" :key="item.id">
                <el-card shadow="hover" style="padding: 5px; margin-bottom: 5px" :style="item.isDeal === 0? '': 'background-color:gray;'">
                  <el-row :gutter="20">
                    <el-col :span="16"><div class="grid-content bg-purple">
                      <el-tag>{{item.name}}</el-tag>
                      <el-button @click.native.prevent="getDetails(item.creator, item.id)" style="float: right; padding: 3px 0" type="text">点击查看发布者信息，方便您即使沟通</el-button>
                      <el-divider></el-divider>
                      <div>{{ item.content.substr(0, 10)+'...' }}</div>
                      <span style="color: darkgray; font-size: 15px">发布时间：{{ timestampToTime(item.createTime) }}</span>|
                      <span style="color: darkgray; font-size: 15px">截止时间：{{ timestampToTime(item.deadline) }}</span>
                    </div></el-col>
                    <el-col :span="8"><div class="grid-content bg-purple">
                      <div>参考图片</div>
                      <div>
                        <el-image
                          style="width: 100%; height: 100px"
                          :src="url"
                          :preview-src-list="srcList">
                        </el-image>
                      </div>
                      <div>报酬 <span style="color: orangered;">{{ item.reward }}</span> 元</div>
                    </div></el-col>
                  </el-row>
                </el-card>
              </div>
            </ul>
            <p style="margin: auto" v-if="loading">加载中...</p>
            <div v-if="noMore">
              <el-empty description="哎呀，人家也是有底线的呀~~~"></el-empty>
            </div>
          </div>
        </el-card>
      </div>
    </div>
    <el-dialog v-dialog-drag title="用户编辑编辑" :visible.sync="dialogFormVisible">
      <div>
        <el-form :model="userData" ref="userForm" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input clearable="clearable" v-model="userData.username"></el-input>
          </el-form-item>
          <el-form-item label="真实姓名" prop="realName" required>
            <el-input clearable="clearable" v-model="userData.realName"></el-input>
          </el-form-item>
          <el-form-item label="您的联系电话" prop="tel">
            <el-input  type="number" clearable="clearable" v-model="userData.tel"></el-input>
          </el-form-item>
          <el-form-item label="您的联系QQ" prop="qq">
            <el-input type="number" clearable="clearable" v-model="userData.qq"></el-input>
          </el-form-item>
          <el-form-item label="您的寝室" prop="bedroomAddr" required>
            <el-input clearable="clearable" v-model="userData.bedroomAddr"></el-input>
          </el-form-item>
          <el-form-item label="介绍" prop="remark">
            <el-input type="textarea" v-model="userData.remark"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 认</el-button>
      </div>
    </el-dialog>
    <el-dialog v-dialog-drag title="用户信息查看" :visible.sync="dialogFormVisible1">
      <div>
        <el-form :model="userData" ref="userForm" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input :disabled="true" clearable="clearable" v-model="userData.username"></el-input>
          </el-form-item>
          <el-form-item label="真实姓名" prop="realName" required>
            <el-input :disabled="true" clearable="clearable" v-model="userData.realName"></el-input>
          </el-form-item>
          <el-form-item label="您的联系电话" prop="tel">
            <el-input :disabled="true" type="number" clearable="clearable" v-model="userData.tel"></el-input>
          </el-form-item>
          <el-form-item label="您的联系QQ" prop="qq">
            <el-input type="number" :disabled="true" clearable="clearable" v-model="userData.qq"></el-input>
          </el-form-item>
          <el-form-item label="您的寝室" prop="bedroomAddr" required>
            <el-input clearable="clearable" :disabled="true" v-model="userData.bedroomAddr"></el-input>
          </el-form-item>
          <el-form-item label="介绍" prop="remark">
            <el-input type="textarea" v-model="userData.remark" :disabled="true"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dealTask">确认任务已处理</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import store from "@/store";
import {getDetails} from "@/api/user";
import {accept, deal, getTask} from "@/api/task";

export default {
  inject: ['reload'],
  name: "personal",

  data(){
    return{
      //
      dialogFormVisible1: false,
      isDealed: '',
      //
      pageNum: 1,
      pageSize: 5,
      tableData: [],
      pageTotal: 5,
      // index for task
      index4task: 0,
      curUid: '',
      // loading for data
      loading: false,
      url: require('../../assets/img/forJava.jpeg'),
      srcList: [
        require('../../assets/img/forGOlang.jpeg'),
        require('../../assets/img/zhiyuan2.jpeg'),
        require('../../assets/img/zhiyuanJob.jpeg')
      ],
      //
      userData: {
        bedroomAddr: "",
        qq: '',
        realName: '',
        remark: "",
        reputation: 100,
        role: "admin",
        tel: 13900000000,
        username: "cj",
      },
      isAdmin: false,
      //
      dialogTableVisible: false,
      dialogFormVisible: false,
      list: [],
      activeName: '1',
      tabClickHandler: ''
    }
  },
  mounted() {
    this.adminView()
    // this.getTasks()
  },
  computed: {
    noMore () {
      return this.pageSize >= this.pageTotal
    },
    disabled () {
      return this.loading || this.noMore
    }
  },
  methods:{
    async dealTask(){
      // get user
      store.dispatch('user/getInfo').then(data => {
        if (data.reputation < 20){
          this.$notify({
            title: '失败',
            message: '抱歉，您的信誉分低于20，不能进行处理操作',
            type: 'error'
          });
        }else{
          // ====================================================
          this.loading = true
          this.acceptMethod()
        }
      })
      this.loading = false
    },
    async acceptMethod(){
      const response = await deal(this.curTid, this.userData.id)
      if (response.code === 200){
        this.$notify({
          title: '成功',
          message: '任务处理成功',
          type: 'success'
        });
        this.loading = false
        this.reload()
      }else{
        this.$notify({
          title: '失败',
          message: '实在抱歉，任务处理发生了意外',
          type: 'error'
        });
        this.loading = false
      }
    },
    // 标签页：
    async handleClick(tab) {
      console.log(tab.index)
      const index = tab.index
      if (index === '0'){
        this.tableData = []
        const response = await getTask({uidCreate: this.curUid,pageNum: this.pageNum, pageSize: this.pageSize})
        console.log('home page here: ', response)
        this.tableData = response.data.list
        this.pageTotal = response.data.total
        console.log('已发布任务：',this.tableData)
      }else if( index === '1'){
        this.tableData = []
        const response = await getTask({uidAccept: this.curUid,pageNum: this.pageNum, pageSize: this.pageSize})
        console.log('home page here: ', response)
        this.tableData = response.data.list
        this.pageTotal = response.data.total
      }else if( index === '2'){
        this.tableData = []
        const response = await getTask({uidCreate: this.curUid,pageNum: this.pageNum, pageSize: this.pageSize})
        console.log('home page here: ', response)
        const alldata = response.data.list
        this.pageTotal = response.data.total
        for (let i = 0; i < alldata.length; i++) {
          if (this.isNull(alldata[i].receiveUserId)){
            this.tableData.push(alldata[i])
          }
        }
      }else{
        console.log('error')
      }
    },
    adminView(){
      store.dispatch('user/getInfo').then(
        response =>{
          this.userData = response
          console.log('我获取到的用户信息为：', response)
          const role = response.role
          this.curUid = response.id
          if (role === 'admin'){
            this.isAdmin = true
          }
        }
      )
    },
    async getTasks() {

      // this.taskForm['pageNum'] = this.pageNum
      // this.taskForm['pageSize'] = this.pageSize
      const response = await getTask({pageNum: this.pageNum, pageSize: this.pageSize})
      console.log('home page here: ', response)
      this.tableData = response.data.list
      this.pageTotal = response.data.total
      console.log('home page here: ', this.tableData)
    },
    submitForm() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          // get user
          store.dispatch('user/getInfo').then(data => {
            //
            data = this.userData
            console.log({id: data.id, data: this.userData})
            this.$store.dispatch('user/update', {id: data.id, data: this.userData})
              .then(() => {
                this.dialogFormVisible = false
                this.$router.push('/main/personal')
              })
              .catch(() => {
                this.loading = false
              })
          })
        } else {
          return false;
        }
      });
    },
    async getDetails(id, curTid){
      this.dialogFormVisible1 = true
      const response = await getDetails(id)
      this.userData = response.data
      this.curTid = curTid
      console.log(curTid,response.data)
    },
    timestampToTime (timestamp) {
      var date = new Date(timestamp) //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + '-'
      var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'
      var D = date.getDate() + ' '
      var h = date.getHours() + ':'
      var m = date.getMinutes() + ':'
      var s = date.getSeconds()
      return Y+M+D+h+m+s
    },
    load () {
      this.loading = true
      setTimeout(() => {
        this.pageSize += 2
        this.getTasks()
        this.loading = false
      }, 2000)
    },
    //判断数据是否为空值，为空返回true,有值为false
    isNull(data) {
      if (!data) return true;
      if (JSON.stringify(data) === '{}') return true;
      if (JSON.stringify(data) === '[]') return true;
      return false;
    }
  }
}
</script>

<style scoped>

</style>

